<template>
  <div class="json-to-xml">
    <el-row :gutter="20">
      <el-col :span="12">
        <el-card class="input-card">
          <template #header>
            <div class="card-header">
              <span>输入 JSON</span>
              <el-button type="primary" @click="convertToXml">转换为 XML</el-button>
            </div>
          </template>
          <el-input
            v-model="inputJson"
            type="textarea"
            :rows="20"
            placeholder="请输入需要转换的 JSON"
          />
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="output-card">
          <template #header>
            <div class="card-header">
              <span>XML 结果</span>
              <el-button type="primary" @click="copyResult">复制结果</el-button>
            </div>
          </template>
          <el-input
            v-model="outputXml"
            type="textarea"
            :rows="20"
            readonly
          />
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'

const inputJson = ref('')
const outputXml = ref('')

const jsonToXml = (obj) => {
  let xml = ''
  for (let prop in obj) {
    xml += obj[prop] instanceof Array ? '' : "<" + prop + ">"
    if (obj[prop] instanceof Array) {
      for (let array in obj[prop]) {
        xml += "<" + prop + ">"
        xml += jsonToXml(obj[prop][array])
        xml += "</" + prop + ">"
      }
    } else if (typeof obj[prop] == "object") {
      xml += jsonToXml(obj[prop])
    } else {
      xml += obj[prop]
    }
    xml += obj[prop] instanceof Array ? '' : "</" + prop + ">"
  }
  return xml
}

const convertToXml = () => {
  try {
    const jsonObj = JSON.parse(inputJson.value)
    const xml = '<?xml version="1.0" encoding="UTF-8"?>\n' + 
                '<root>' + jsonToXml(jsonObj) + '</root>'
    outputXml.value = xml
    ElMessage.success('转换成功')
  } catch (error) {
    ElMessage.error('无效的 JSON 格式')
  }
}

const copyResult = async () => {
  try {
    await navigator.clipboard.writeText(outputXml.value)
    ElMessage.success('复制成功')
  } catch (error) {
    ElMessage.error('复制失败')
  }
}
</script>

<style scoped>
.json-to-xml {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.input-card,
.output-card {
  height: 100%;
}

:deep(.el-textarea__inner) {
  font-family: monospace;
  min-height: 500px !important;
}
</style> 